package demo5;

import java.util.ArrayList;
import java.util.LinkedList;

public class test {
        static class LinkNode {
        public int val;
        public LinkNode next;
        public LinkNode(int val) {
            this.val = val;
        }
    }
    public LinkNode head;
    //返回倒数第K个结点
    public int returnKey(LinkNode head,int k) {
        if(head == null) {
            return -1;
        }
        //对k做合法性判断
        if(k < 0) {
            return -1;
        }
        LinkNode fast = head;
        LinkNode slow = head;
        while((k-1) != 0) {
            fast = fast.next;
            //如果K大于链表的长度
            if(fast == null) {
                return -1;
            }
            k--;
        }
        while(fast != null) {
            fast = fast.next;
            slow = slow.next;
        }
        return slow.val;
    }
    public void removeAllKey(int key) {
        if(head == null) {
            return;
        }
//        while(head.val == key) {
//            head = head.next;
//        }
        LinkNode cur = head;
        LinkNode curNext = head.next;
        while(curNext != null) {
            if(curNext.val == key) {
                cur.next = curNext.next;
                curNext = curNext.next;
            }else {
                cur = curNext;
                curNext = curNext.next;
            }
        }
        //很巧妙
        if(head.val == key) {
            head = head.next;
        }
    }
    public void createNode() {
        LinkNode node1 = new LinkNode(12);
        LinkNode node2 = new LinkNode(23);
        LinkNode node3 = new LinkNode(96);
        LinkNode node4 = new LinkNode(48);
        LinkNode node5 = new LinkNode(26);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        head = node1;
    }

    public boolean empty() {
        if(size() == 0) {
            return true;
        }
        return false;
    }

    public int size() {
        LinkNode cur = head;
        int count = 0;
        while(cur != null) {
            count++;
            cur = cur.next;
        }
        return count;
    }
    public void display() {
        LinkNode cur = head;
        while(cur != null) {
            System.out.print(cur.val + " ");
            cur = cur.next;
        }
        System.out.println();
    }
    public void addFirst(int data) {
        LinkNode node = new LinkNode(data);
        node.next = head;
        head = node;
    }
    public void addLast(int data) {
        LinkNode node = new LinkNode(data);
        if(head == null) {
            head = node;
        }else {
            LinkNode cur = head;
            while(cur != null) {
                cur = cur.next;
            }
            cur.next = node;
        }
    }

    public static void main(String[] args) {

        ArrayList<Integer> arrayList = new ArrayList<>();

        arrayList.add(1);
    }
}
